<?php
require_once  dirname(dirname(dirname(__FILE__))). DIRECTORY_SEPARATOR.'vendor'. DIRECTORY_SEPARATOR . 'autoload.php';
use Pheanstalk\Pheanstalk;
$host = PHP_OS == "Linux" ? "127.0.0.1" : "10.0.0.200";
$psk = Pheanstalk::create($host,11300,20);

while (true) {
    try {
        $job = $psk->watchOnly('sqlAsync')->reserve();
        $data = $job->getData();
        if ($data) {
            $param = json_decode($data, true);
            $res = execSql($param);
            if ($res) {
                //消费成功
                $psk->watchOnly('sqlAsync')->delete($job);
                $fileName = PHP_OS == "Linux" ? "/var/www/data/log/beanstalk_sql.log" : "D:/log/beanstalk_sql.log";
                file_put_contents($fileName, '执行成功!' . date('Y-m-d H:i:s') . ' | ' . $data . PHP_EOL, FILE_APPEND);
            } else {
                //sql执行失败,将消息状态改为bury
                $psk->watchOnly('sqlAsync')->bury($job);
            }
        }
    } catch (\Pheanstalk\Exception\ServerException $e) {
        $fileName = PHP_OS == "Linux" ? "/var/www/data/log/beanstalk_error.log" : "D:/log/beanstalk_error.log";
        file_put_contents($fileName, date('Y-m-d H:i:s') . ' | ' . $e->getMessage() . ' | ' . $e->getTraceAsString() . ' | ' . $data . PHP_EOL, FILE_APPEND);
    }
    usleep(5000);
}


function execSql($params)
{
    list($sql, $data) = [$params['sql'], $params['data']];
    $dbms = 'mysql';
    $host = "10.0.0.200";
    $dbName = "wyq";
    $dsn = "$dbms:host=$host;dbname=$dbName";
    $opts = [
        PDO::ATTR_TIMEOUT => 2, //连接数据库的超时秒数
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //错误模式 这个模式会抛出错误和错误的详细信息
        PDO::ATTR_PERSISTENT => TRUE, //长连接
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8MB4',
    ];
    try {
        $pdo = new PDO($dsn, 'wyq', 'WYQGG123@mysql', $opts);
        $sth = $pdo->prepare($sql);
        $sth->execute($data);
    } catch (PDOException $e) {
        //记录sql错误日志
        $fileName = PHP_OS == "Linux" ? "/var/www/data/log/beanstalk_sql_error.log" : "D:/log/beanstalk_sql_error.log";
        file_put_contents($fileName, "执行失败!" . date('Y-m-d H:i:s') . ' | ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
        return false;
    }
    return true;
}